/**
 * Copyright 2008 by Robert Konigsberg
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the same terms as Perl.
 *
 * @see http://www.perl.com/perl/misc/Artistic.html
 */
package visitor.maze;

/**
 * Builds {@link Maze} instances.
 *
 * @author kberg
 */
public class MazeBuilder {

  private Maze maze = new Maze();

  /**
   * Creates a connection from the first room to the second room, in the
   * supplied direction. The rooms are created if they did not exist yet.
   */
  public MazeBuilder oneWayConnect(int firstId, int secondId, Direction direction) {
    Room first = getOrCreateRoom(firstId);
    Room second = getOrCreateRoom(secondId);
    first.setExit(direction, second);
    return this;
  }

  /**
   * Creates a connection from the first room to the second room, in the
   * supplied direction, and a connection from the second room to the first room
   * in the opposite direction. The rooms are created if they did not exist yet.
   */
  public MazeBuilder twoWayConnect(int firstId, int secondId, Direction direction) {
    oneWayConnect(firstId, secondId, direction);
    oneWayConnect(secondId, firstId, direction.opposite());
    return this;
  }

  private Room getOrCreateRoom(int id) {
    Room room = maze.getRoom(id);
    if (room == null) {
      room = new Room(id);
      maze.addRoom(room);
    }
    return room;
  }

  /**
   * Return the built-maze. This maze is still mutable with the builder, so once
   * once this method is called this instance should no longer be used.
   */
  public Maze getMaze() {
    return maze;
  }
}
